<template>
  <view class="container">
    <view class="input-section">
      <input
        v-model="newTodo"
        class="todo-input"
        placeholder="输入新任务"
        @confirm="addTodo"
      />
      <button class="add-button" @click="addTodo">添加</button>
    </view>

    <view class="todo-list">
      <view
        v-for="todo in todos"
        :key="todo.id"
        class="todo-item"
        :class="{ completed: todo.completed }"
      >
        <text class="todo-text">{{ todo.text }}</text>
        <view class="actions">
          <button class="toggle-btn" @click="toggleTodo(todo.id)">
            {{ todo.completed ? '重做' : '完成' }}
          </button>
          <button class="delete-btn" @click="removeTodo(todo.id)">删除</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useTodoStore } from '@/store/todo';
import { useUserStore } from '@/store/user';

const newTodo = ref('');
const store = useTodoStore();
const userStore = useUserStore();

onMounted(() => {
  if (!userStore.isLoggedIn) {
    uni.redirectTo({ url: '/pages/login/login' });
  }
});

const addTodo = () => {
  if (newTodo.value.trim()) {
    store.addTodo(newTodo.value.trim());
    newTodo.value = '';
  }
};

const toggleTodo = (id: number) => store.toggleTodo(id);
const removeTodo = (id: number) => store.removeTodo(id);

const todos = store.todos;
</script>

<style lang="scss">
.container {
  padding: 20rpx;
}

.input-section {
  display: flex;
  gap: 10rpx;
  margin-bottom: 30rpx;
}

.todo-input {
  flex: 1;
  border: 1px solid #ddd;
  padding: 15rpx;
  border-radius: 8rpx;
}

.add-button {
  background: #007aff;
  color: white;
  padding: 0 30rpx;
  border-radius: 8rpx;
}

.todo-list {
  border-radius: 10rpx;
  overflow: hidden;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #eee;

  &.completed .todo-text {
    text-decoration: line-through;
    color: #999;
  }
}

.actions {
  display: flex;
  gap: 10rpx;
}

.toggle-btn {
  background: #4cd964;
  color: white;
  padding: 8rpx 15rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.delete-btn {
  background: #dd524d;
  color: white;
  padding: 8rpx 15rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}
</style>
